package com.jyx.web.socket.socket;

import java.io.IOException;
//import java.util.ArrayList;
import java.util.Collection;
//import java.util.List;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

//import org.springframework.web.socket.TextMessage;

//import org.springframework.web.socket.CloseStatus;
//import org.springframework.web.socket.WebSocketHandler;
//import org.springframework.web.socket.WebSocketMessage;
//import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
import com.jyx.web.socket.config.WebSocketConfig;
import com.jyx.web.socket.message.TextMessage;
import com.jyx.web.socket.session.SessionCacheManager;

// 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端。注解的值将被用于监听用户连接的终端访问URL地址
@ServerEndpoint(value = "/webSocketTest",configurator = WebSocketConfig.class)
public class WebSocketTest/* implements WebSocketHandler*/{

	private SessionCacheManager sessionCacheManager = new SessionCacheManager();
	
	// 他们定义了当一个新用户连接的时候所调用的方法。
	@OnOpen
	public void onOpen(Session session){
		System.out.println("webSocket连接已建立，sessionId:"+session.getId());
		sessionCacheManager.put(session);
		
		// 给所有用户推送消息
		TextMessage message = new TextMessage();
		message.setFrom(session.getId());
		message.setTo("all");
		message.setContent("用户："+session.getId()+",上线了！");
		
		sendMessage(message,session);
	}
	
	// 他们定义了当一个新用户断开的时候所调用的方法。
	@OnClose
	public void onClose(Session session){
		System.out.println("webSocket连接已关闭，sessionId"+session.getId());
		sessionCacheManager.remove(session.getId());
		
	}
	
	
	@OnError
	public void onError(Session session,Throwable e){
		System.out.println("webSocket连接错误，sessionId"+session.getId());
		e.printStackTrace();
	}
	
	// 这个注解定义了当服务器接收到客户端发送的消息时所调用的方法。
	// 注意：这个方法可能包含一个javax.websocket.Session可选参数。如果有这个参数，容器将会把当前发送消息客户端的连接Session注入进去。
	@OnMessage
	public void onMessage(Session session,String message){
		System.out.println("webSocket收到消息"+message);
		
		TextMessage textMessage = JSON.parseObject(message,TextMessage.class);
		textMessage.setFrom(session.getId());
		sendMessage(textMessage,session);
	}

	
	public void sendMessage(TextMessage message,Session curSession){
		String json = JSON.toJSONString(message);
		if(message.getTo().equals("all")){
			Collection<Session> allSession = sessionCacheManager.getAll();
			for (Session session : allSession) {
				try {
					session.getBasicRemote().sendText(json);
				} catch (IOException e) {
					continue;
				}
			}
		}else{
			try {
				Session toSession = sessionCacheManager.get(message.getTo());
				toSession.getBasicRemote().sendText(json);
				System.out.println("发送成功!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/*
	private static final List<WebSocketSession> userList = new ArrayList<>();
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		userList.add(session);
		JSONObject json = new JSONObject();
		json.put("to","all");
		json.put("from", "系统");
		json.put("content", ("欢迎游客" + session.getId() + "上线了"));
		TextMessage textMessage = new TextMessage(json.toJSONString().getBytes());
		this.sendMessageToAll(textMessage);
		
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		JSONObject msg = JSONObject.parseObject(message.getPayload().toString());
		String to = msg.getString("to");
		String content = msg.getString("content");
		msg.put("from",session.getId());
		TextMessage textMessage = new TextMessage(msg.toJSONString().getBytes());
		this.sendMessageToUser(to, textMessage);
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		userList.remove(session);
		JSONObject json = new JSONObject();
		json.put("to","all");
		json.put("from", "系统");
		json.put("content", ("游客" + session.getId() + "离线了"));
		TextMessage textMessage = new TextMessage(json.toJSONString().getBytes());
		this.sendMessageToAll(textMessage);
	}

	
	
	private void sendMessageToAll(WebSocketMessage<?> message){
		for (WebSocketSession webSocketSession : userList) {
			try {
				webSocketSession.sendMessage(message);
			} catch (IOException ok) {
			}
		}
	}
	
	
	private void sendMessageToUser(String to, WebSocketMessage<?> message){
		for (WebSocketSession webSocketSession : userList) {
			if(webSocketSession.getId().equals(to)){
				try {
					webSocketSession.sendMessage(message);
				} catch (IOException e) {
				}
				break;
			}
		}
	}
	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
*/
	
}
